package nl.nhl.idp.Views;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.Style;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class StopButtonView extends View
{
	private Paint bgStrokePaint;
	private Paint bgPaint;
	private Paint textPaint;
	private int radius;
	private int centerX;
	private int centerY;
	private OnClickListener clickListener;
	
	@Override
	public void setOnClickListener(OnClickListener listener)
	{
		clickListener = listener;
	}
	

	public StopButtonView(Context context)
	{
		this(context, null);
	}

	public StopButtonView(Context context, AttributeSet attrs)
	{
		this(context, attrs, 0);
	}
	
	public StopButtonView(Context context, AttributeSet attrs, int defStyle)
	{
		super(context, attrs, defStyle);
		
		setFocusable(true);
		bgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
		bgPaint.setColor(Color.RED);
		bgPaint.setStyle(Style.FILL);
		
		bgStrokePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
		bgStrokePaint.setColor(Color.rgb(128, 0, 0));
		bgStrokePaint.setStrokeWidth(3);
		bgStrokePaint.setStyle(Style.STROKE);
		
		textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
		textPaint.setColor(Color.WHITE);
		textPaint.setStyle(Style.STROKE);
		textPaint.setTextAlign(Align.CENTER);
		textPaint.setTextSize(30);
	}
	
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
	{
		// TODO Auto-generated method stub
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		
		// Here we make sure that we have a perfect circle
		int measuredWidth = MeasureSpec.getSize(widthMeasureSpec);
		int measuredHeight = MeasureSpec.getSize(heightMeasureSpec);
		
		setMeasuredDimension(measuredWidth, measuredHeight);
		
		centerX = getWidth()/2;
		centerY = getHeight()/2;
		radius = (centerX < centerY? centerX:centerY)-3;
	}
	
	@Override
	protected void onDraw(Canvas canvas)
	{
		canvas.drawCircle(centerX, centerY, radius, bgPaint);
		canvas.drawCircle(centerX, centerY, radius, bgStrokePaint);
		canvas.drawText("STOP", centerX, centerY+10, textPaint);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event)
	{
		if (clickListener != null)
		{
			switch (event.getAction())
			{
				case MotionEvent.ACTION_DOWN:
				{
					bgPaint.setColor(Color.rgb(128, 0, 0));
					bgStrokePaint.setColor(Color.RED);
					invalidate();
					
					clickListener.onClick(this);
				}break;
				case MotionEvent.ACTION_UP:
				{
					bgPaint.setColor(Color.RED);	
					bgStrokePaint.setColor(Color.rgb(128, 0, 0));
					invalidate();
					
				}break;
			}
			
			return true;
		}
		return false;
	}
}
